package com.dede.monochromatism.util

import android.content.ComponentName
import android.content.ContentResolver
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.MediaStore.Images.ImageColumns
import android.provider.Settings
import com.dede.monochromatism.service.PackageChangeListenerServer


/**
 * @author hsh
 * @time 2017/6/25 025 7:25 下午.
 * @doc
 */
object Util {

    fun getPackageInfo(context: Context, packageName: String): PackageInfo? {
        return try {
            context.packageManager.getPackageInfo(packageName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 获取默认输入法
     * default_input_method=com.iflytek.inputmethod/.FlyIME
     */
    fun getDefaultInputMethod(context: Context): String {
        var defaultInputMethod = ""
        try {
            val defaultInputMethodClassStr = Settings.Secure.getString(context.contentResolver,
                    android.provider.Settings.Secure.DEFAULT_INPUT_METHOD)
            if (defaultInputMethodClassStr.isNotEmpty())
                defaultInputMethod = defaultInputMethodClassStr.split("/")[0]
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
        }

        return defaultInputMethod
    }

    /**
     * 判断当前应用的辅助功能服务是否开启
     */
    fun accessibilitySettingsIsOpen(context: Context): Boolean {
        var accessibilityEnabled = 0
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.contentResolver,
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED)
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
        }

        if (accessibilityEnabled == 1) {
            try {
                val services = Settings.Secure.getString(context.contentResolver,
                        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
                if (services != null) {
                    return services.toLowerCase().contains(context.packageName.toLowerCase())
                }
            } catch (e: Settings.SettingNotFoundException) {
                e.printStackTrace()
            }
        }
        return false
    }

    /**
     * 打开无障碍服务
     */
    fun openAccessibilitySettings(context: Context, callBack: (Exception) -> Unit = {}): Boolean {
        if (!accessibilitySettingsIsOpen(context)) {
            try {
                val services = Settings.Secure.getString(context.contentResolver,
                        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)

                val flattenToString = ComponentName(context, PackageChangeListenerServer::class.java).flattenToString()

                return Settings.Secure.putString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                        services + ":" + flattenToString)
            } catch (e: Settings.SettingNotFoundException) {
                e.printStackTrace()
                callBack(e)
            } catch (e: SecurityException) {
                e.printStackTrace()
                callBack(e)
            }
            return false
        } else {
            return true
        }
    }

    /**
     * 关闭无障碍服务
     */
    fun closeAccessibilitySettings(context: Context): Boolean {
        if (accessibilitySettingsIsOpen(context)) {
            try {
                val services = Settings.Secure.getString(context.contentResolver,
                        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)

                val flattenToString = ComponentName(context, PackageChangeListenerServer::class.java).flattenToString()

                if (services.contains(flattenToString).not())
                    return true

                val builder = StringBuilder()
                services.split(":")
                        .filter { it.isNotBlank() && it != flattenToString }
                        .forEachIndexed { index, s ->
                            if (index != 0)
                                builder.append(":")
                            builder.append(s)
                        }
                return Settings.Secure.putString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, builder.toString())
            } catch (e: Settings.SettingNotFoundException) {
                e.printStackTrace()
            } catch (e: SecurityException) {
                e.printStackTrace()
            }
            return false
        } else {
            return true
        }
    }

    /**
     * 通过uri获取路径
     */
    fun getRealFilePath(context: Context, uri: Uri): String? {
        val scheme = uri.scheme
        var data: String? = null
        if (scheme == null)
            data = uri.path
        else if (ContentResolver.SCHEME_FILE == scheme) {
            data = uri.path
        } else if (ContentResolver.SCHEME_CONTENT == scheme) {
            val cursor = context.contentResolver.query(uri, arrayOf(ImageColumns.DATA), null, null, null)
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    val index = cursor.getColumnIndex(ImageColumns.DATA)
                    if (index > -1) {
                        data = cursor.getString(index)
                    }
                }
                cursor.close()
            }
        }
        return data
    }


    fun getSimulateColorSpaceState(context: Context): Boolean {
        val cr = context.contentResolver
        return try {
            val state = Settings.Secure.getInt(cr, "accessibility_display_daltonizer_enabled")
            if (state == 0)
                false
            else {
                Settings.Secure.getInt(cr, "accessibility_display_daltonizer") == 0
            }
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 设置模拟颜色空间的状态
     *
     * @author hsh
     * @param context
     * @param state
     * @param callBack
     * @return true 成功，false 失败
     */
    fun setSimulateColorSpaceState(context: Context, state: Boolean, callBack: (Exception) -> Unit = {}): Boolean {
        val cr = context.contentResolver
        try {
            /**
             * 系统隐藏常量
             * android api 25源码 android.provider.Settings 5313行
             * android.provider.Settings.Secure
             * 是否启用模拟颜色空间
             * 0 停用, 1 启用
             * public static final String ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED = "accessibility_display_daltonizer_enabled"
             * 模拟颜色空间模式
             * 0 全色盲, 1 红色弱视, 2 绿色弱视, 3 蓝色弱视
             * public static final String ACCESSIBILITY_DISPLAY_DALTONIZER ="accessibility_display_daltonizer"
             */
            return if (state && !getSimulateColorSpaceState(context)) {
                val enable = Settings.Secure.putInt(cr, "accessibility_display_daltonizer_enabled", 1)
                val value = Settings.Secure.putInt(cr, "accessibility_display_daltonizer", 0)
                enable && value
            } else if (!state && getSimulateColorSpaceState(context)) {
                Settings.Secure.putInt(cr, "accessibility_display_daltonizer_enabled", 0)
            } else {
                true
            }
        } catch (e: SecurityException) {
            e.printStackTrace()
            callBack(e)
            return false
        }
    }
}
